#include "functions.h"

void archives_sort(){
  int i;

  // Layer 0
  population_sort( archive[ 0 ].individuals, each_individuals * 2 );

  // Layer L - 1
  population_sort( archive[ number_of_layers - 1 ].individuals, each_individuals * 2 );

  // Layer from 1 to L - 2
  for( i = 1; i < number_of_layers - 1 ; i++ )
    population_sort( archive[ i ].individuals, each_individuals * 3 );

}

void print_archives(){
  int i, j, k;

  // Layer 1
  for( j = 0; j < each_individuals * 2; j++ ){
    printf( "0 : %f : ", archive[ 0 ].individuals[ j ].function_value );

    for( k = 0; k < number_of_dimensions; k++ ){
      printf("%f\t", archive[ 0 ].individuals[ j ].design_variables[ k ] );
    }
    printf("\n");
  }

  // Layer from 2 to L - 2
  for( i = 1; i < number_of_layers - 1 ; i++ ){
    for( j = 0; j < each_individuals * 3; j++ ){
      printf( "%d : %f : ", i, archive[ i ].individuals[ j ].function_value );
      
      for( k = 0; k < number_of_dimensions; k++ ){
	printf("%f\t", archive[ i ].individuals[ j ].design_variables[ k ] );
      }
      printf("\n");
    }
  }

  // Layer L - 1
  for( j = 0; j < each_individuals * 2 ; j++ ){
    printf( "%d : %f : ", number_of_layers - 1, archive[ number_of_layers - 1 ].individuals[ j ].function_value );

    for( k = 0; k < number_of_dimensions; k++ ){
      printf("%f\t", archive[ number_of_layers - 1 ].individuals[ j ].design_variables[ k ] );
    }
    printf("\n");
  }
  
}

void initialize_archives(){
  int i, j;

  // malloc for archive 
  archive = ( ARCHIVE * ) malloc( sizeof( ARCHIVE ) * number_of_layers );

  // Layer 0
  archive[ 0 ].individuals = ( INDIVIDUAL * ) malloc( sizeof( INDIVIDUAL ) * each_individuals * 2 );
  
  // Layer L - 1
  archive[ number_of_layers - 1 ].individuals = ( INDIVIDUAL * ) malloc( sizeof( INDIVIDUAL ) * each_individuals * 2 );

  // Layer 0 and L - 1
  for( i = 0; i < each_individuals * 2; i++ ){
    archive[ 0 ].individuals[ i ].design_variables = ( double * ) malloc( sizeof( double ) * number_of_dimensions );
    archive[ number_of_layers - 1 ].individuals[ i ].design_variables = ( double * ) malloc( sizeof( double ) * number_of_dimensions );
  }

  // Layer 1 to L - 2
  for( i = 1; i < number_of_layers - 1 ; i++ ){
    archive[ i ].individuals = ( INDIVIDUAL * ) malloc( sizeof( INDIVIDUAL ) * each_individuals * 3 );

    for( j = 0; j < each_individuals * 3; j++ )
      archive[ i ].individuals[ j ].design_variables = ( double * ) malloc( sizeof( double ) * number_of_dimensions );
  }

}
